package com.warm.mf.core.domain;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.warm.core.utils.StringUtils;
import lombok.Getter;
import lombok.Setter;

/**
 * 分页数据
 *
 * @author warm
 */
@Getter
@Setter
public class QueryParam {
    /**
     * 当前记录起始索引
     */
    private Integer pageNum = 1;

    /**
     * 每页显示记录数
     */
    private Integer pageSize = 10;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     */
    private String isAsc = "asc";

    /**
     * 分页参数合理化
     */
    private Boolean reasonable = true;

    public String getOrderBy() {
        if (StrUtil.isEmpty(orderByColumn)) {
            return "";
        }
        return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
    }

    public void setIsAsc(String isAsc) {
        if (StrUtil.isNotEmpty(isAsc)) {
            // 兼容前端排序类型
            if ("ascending".equals(isAsc)) {
                isAsc = "asc";
            } else if ("descending".equals(isAsc)) {
                isAsc = "desc";
            }
            this.isAsc = isAsc;
        }
    }

    public Boolean getReasonable() {
        if (ObjectUtil.isNull(reasonable)) {
            return Boolean.TRUE;
        }
        return reasonable;
    }

    public static <T> Page<T> getPage(QueryParam queryParam, QueryWrapper query) {
        if (StrUtil.isNotBlank(queryParam.getOrderBy())) {
            query.orderBy(queryParam.getOrderBy());
        }
        return Page.of(queryParam.getPageNum(), queryParam.getPageSize());
    }

    public static <T> Page<T> getPage(QueryParam queryParam) {
        return Page.of(queryParam.getPageNum(), queryParam.getPageSize());
    }

}
